import uuid
from datetime import datetime, timedelta
import random
import string
import argparse
from decimal import Decimal

# 定义 ProductCatType 枚举
class ProductCatType:
    INTERNAL = "'INTERNAL'"
    MARKET = "'MARKET'"
    EXPERIMENTAL = "'EXPERIMENTAL'"

def generate_random_string(length):
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for _ in range(length))

def generate_random_description():
    return f"Description for {generate_random_string(50)}"

def generate_random_icon():
    return f"http://example.com/icons/{generate_random_string(10)}.png"

def generate_random_amount():
    return Decimal(f"{random.uniform(10.00, 1000.00):.4f}")

def generate_random_publish_at(base_datetime):
    offset_days = random.randint(0, 365)
    return (base_datetime + timedelta(days=offset_days)).strftime('%Y-%m-%d %H:%M:%S')

def generate_fixed_app_id(index, num_groups):
    # Generate a fixed app_id based on the index and total number of groups
    group_number = (index - 1) % num_groups + 1
    return f"'app_{group_number}'"

def generate_fixed_tenant_id(index, num_groups):
    # Generate a fixed tenant_id based on the index and total number of groups
    group_number = (index - 1) % num_groups + 1
    return f"'tenant_{group_number}'"

def generate_random_type():
    return random.choice([ProductCatType.INTERNAL, ProductCatType.MARKET, ProductCatType.EXPERIMENTAL])

def generate_record(index, base_datetime, num_groups):
    record_id = str(uuid.uuid4())
    parent_id = str(uuid.uuid4()) if random.choice([True, False]) else None
    code = generate_random_string(10)
    created_by = str(uuid.uuid4())
    updated_by = str(uuid.uuid4())

    app_id = generate_fixed_app_id(index, num_groups)
    tenant_id = generate_fixed_tenant_id(index, num_groups)
    product_type = generate_random_type()

    record = {
        'id': f"'{record_id}'",
        'name': f"'Category {index}'",
        'description': f"'{generate_random_description()}'",
        'icon': f"'{generate_random_icon()}'",
        'sort': str(index),
        'amount_market': f"'{generate_random_amount()}'",
        'publish_at': f"'{generate_random_publish_at(base_datetime)}'",
        'parent_id': f"'{parent_id}'" if parent_id else 'NULL',
        'code': f"'{code}'",
        'created_by': f"'{created_by}'",
        'created_at': f"'{generate_random_publish_at(base_datetime)}'",
        'updated_by': f"'{updated_by}'",
        'updated_at': f"'{generate_random_publish_at(base_datetime)}'",
        'is_enabled': 'true' if random.choice([True, False]) else 'false',
        'language': "'zh-CN'",
        'version': "'1.0.0'",
        'tenant_id': tenant_id,
        'app_id': app_id,
        'c_metadata': f"'{{\"key\":\"value{index}\"}}'",
        'type': product_type
    }

    return record, record_id

def generate_sql_records(num_records, base_datetime, num_groups):
    insert_records = []
    delete_records = []

    columns = [
        'id', 'name', 'description', 'icon', 'sort', 'amount_market', 'publish_at',
        'parent_id', 'code', 'created_by', 'created_at', 'updated_by', 'updated_at',
        'is_enabled', 'language', 'version', 'tenant_id', 'app_id', 'c_metadata', 'type'
    ]

    for i in range(1, num_records + 1):
        record, record_id = generate_record(i, base_datetime, num_groups)
        values = ','.join(record[col] for col in columns)
        insert_statement = f"INSERT IGNORE INTO tk_product_cat ({','.join(columns)}) VALUES ({values});"
        insert_records.append(insert_statement)
        delete_statement = f"DELETE FROM tk_product_cat WHERE id = '{record_id}';"
        delete_records.append(delete_statement)

    return insert_records, delete_records

def main():
    parser = argparse.ArgumentParser(description="生成 SQL 插入和删除语句用于测试数据")
    parser.add_argument('--num_records', type=int, default=34, help='生成的记录数量')
    parser.add_argument('--output_file_base', type=str, default='product-data', help='输出 SQL 文件的基础名称（例如，product-data 将生成 product-data-insert.sql 和 product-data-delete.sql）')

    args = parser.parse_args()

    num_groups = random.randint(3, 5)  # 固定为 3 到 5 组之间

    base_datetime = datetime.now()
    insert_records, delete_records = generate_sql_records(args.num_records, base_datetime, num_groups)

    insert_file_name = f"{args.output_file_base}-insert.sql"
    delete_file_name = f"{args.output_file_base}-delete.sql"

    with open(insert_file_name, 'w') as insert_f:
        for record in insert_records:
            insert_f.write(f"{record}\n")

    with open(delete_file_name, 'w') as delete_f:
        for record in delete_records:
            delete_f.write(f"{record}\n")

    print(f"已生成 {args.num_records} 条插入语句在 {insert_file_name}")
    print(f"已生成 {args.num_records} 条删除语句在 {delete_file_name}")

if __name__ == "__main__":
    main()
